<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerCell="{ column }">
        <template v-if="column.key === 'effective'">
          <span> 有效余额 </span>
          <Tooltip>
            <template #title>
              <div>有效期：指分配给机构的资源自分配成功起1年内有效，过期则失效不能使用。</div>
              <div>有效余额：指有效期内的手机号授权剩余次数总和。</div></template
            >
            <QuestionCircleFilled />
          </Tooltip>
        </template>
        <template v-else-if="column.key === 'isAuthorization'">
          <span> 小程序授权 </span>
          <Tooltip>
            <template #title
              >指机构管理员授权将自己的小程序授权给第三方平台，允许获取开发，上架等权限。</template
            >
            <QuestionCircleFilled />
          </Tooltip>
        </template>
        <template v-else>
          <span>{{ column.customTitle }}</span>
        </template>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="getActions(record)" />
        </template>
      </template>

      <template #toolbar>
        <div class="flex-warp">
          <span class="desc"
            >平台可分配/总额：<span style="color: #2a7dc9">
              {{ OrderUsageResult?.all - OrderUsageResult?.used }}</span
            >/{{ OrderUsageResult?.all }}
          </span>
          <a-button type="primary" @click="handleRecharge" style="margin-left: 10px"
            >立即充值</a-button
          >
          <a-button type="primary" @click="handleViewRecord" style="margin-left: 10px"
            >手机验证分配记录</a-button
          >
        </div>
      </template>

      <!-- 有效余额 -->
      <template #effective="{ record }">
        {{ record.effective }}
        <MenuOutlined @click="handleShowRecord(record)" />
      </template>

      <template #isAuthorization="{ record }">
        {{ record.isAuthorization === IsAuthorizationEnum.AUTHORIZED ? '已授权' : '未授权' }}
      </template>
    </BasicTable>

    <!-- 额度分配 -->
    <AllocationModal @register="register" @reload="refresh" />

    <!-- 分配记录 -->
    <RecordModal @register="registerRecord" />
  </div>
</template>

<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, ActionItem } from '@/components/Table';
  import AllocationModal from './modal/allocation.vue';
  import RecordModal from './modal/record.vue';
  import { Tooltip } from 'ant-design-vue';
  import { MenuOutlined, QuestionCircleFilled } from '@ant-design/icons-vue';

  import { PhoneAuthList, OrderUsage } from '@/api/phoneAuth/phoneAuthList';
  import { IOrderUsageResult, IPhoneAuthListResult } from '@/api/phoneAuth/phoneAuthList/type';
  import { getBasicColumns } from './tableData';
  import Dictionary from '@/utils/dictionary';
  import { useModal } from '@/components/Modal';
  import { ref } from 'vue';
  import { IsAuthorizationEnum } from '@/enums/phoneAuthEnum';
  import { useRouter } from 'vue-router';

  const dicts = Dictionary.getLocalMulti(['isAuthorization']);
  const router = useRouter();

  const [registerTable, { reload }] = useTable({
    title: '',
    api: PhoneAuthList,
    columns: getBasicColumns(),
    rowKey: 'id',
    useSearchForm: true,
    formConfig: {
      labelWidth: 100,
      schemas: [
        {
          field: `keyword`,
          label: `关键词`,
          component: 'Input',
          colProps: {
            span: 4,
          },
          componentProps: {
            placeholder: '机构编号、名称搜索',
          },
        },
        {
          field: `isAuthorization`,
          label: `小程序授权`,
          component: 'Select',
          colProps: {
            span: 4,
          },
          componentProps: {
            options: dicts.isAuthorization.map((item) => {
              return {
                label: item.dictLabel,
                value: item.dictValue,
                key: item.dictValue,
              };
            }),
          },
        },
      ],
    },
    showTableSetting: true,
    tableSetting: { fullScreen: true },
    showIndexColumn: true,
    clickToRowSelect: false,
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: () => {
      getOrderUsage();
    },
  });

  const getActions = (record: IPhoneAuthListResult) => {
    let actions: ActionItem[] = [
      {
        label: '额度分配',
        tooltip: '额度分配',
        onClick: handleAllocation.bind(null, record),
        disabled: record.isAuthorization === IsAuthorizationEnum.UNAUTHORIZED, //未授权
      },
    ];

    return actions;
  };

  //跳转至立即充值页面
  function handleRecharge() {
    window.open(
      'https://fuwu.weixin.qq.com/service-provider/wxacharge?wxacharge=%2Fservice-provider%2Fcharge',
    );
  }

  //跳转至短信分配管理页面
  function handleViewRecord() {
    router.push({
      path: '/phoneAuth/allocationRecord',
    });
  }

  const [register, { openModal }] = useModal();

  function handleAllocation(row: any) {
    openModal(true, {
      row: {
        ...row,
        allotmentTotal: OrderUsageResult.value.all - OrderUsageResult.value.used,
      },
    });
  }

  const OrderUsageResult = ref<IOrderUsageResult>({
    all: 0,
    used: 0,
  });

  /** 获取平台可分配/总额 */
  async function getOrderUsage() {
    let res = await OrderUsage();
    OrderUsageResult.value = res;
  }

  /** 刷新数据 */
  function refresh() {
    reload();
    getOrderUsage();
  }

  const [registerRecord, { openModal: openRecordModal }] = useModal();

  /** 显示分配记录 */
  function handleShowRecord(row: any) {
    openRecordModal(true, {
      row,
    });
  }
</script>

<style lang="less" scoped>
  .flex-warp {
    flex: 1;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .desc {
      margin-left: 10px;
      font-size: 18px;
      font-weight: bold;
    }
  }
</style>
